import axios from 'axios'
import router from '@/routes/index.js'
import { getToken, removeToken } from '@/utils/token.js'

const request = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL,
  timeout: 7000
})

request.interceptors.request.use(
  (config) => {
    const token = getToken()
    if (token) {
      config.headers.Authorization = 'Bearer ' + token
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

request.interceptors.response.use(
  (response) => {
    return response
  },
  (error) => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          removeToken()
          window.location.reload()
          break
        default:
      }
    } else if (error.request) {
      if (error.message.includes('timeout')) {
      } else {
      }
    } else {
    }
    return Promise.reject(error)
  }
)

export default request
